package com.fingard.dsp.bank.directbank.epay01;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IAcceptNotice;
import com.fingard.dsp.bank.helpers.SeqSingleInfo;
import com.fingard.dsp.bank.helpers.SeqSingleInfoHelper;
import com.fingard.generalobj.NoticeReq;
import com.fingard.generalobj.NoticeResp;
import com.fingard.io.FileHelper;
import com.fingard.net.listener.SocketReceiver;
import com.fingard.text.StringHelper;

import java.io.File;
import java.util.Date;

public class EPAY01AcceptNotice extends EPAY01Base implements IAcceptNotice {
    @Override
    public NoticeResp dealNotice(NoticeReq pNtReq) throws Exception {
        NoticeResp resp = new NoticeResp();

        synchronized (bankFront.mutex7516) {
            String p_req = pNtReq.getReqString();
            WriteBankLogLn("接收到请求数据内容为：\r\n" + pNtReq.getFullString());

            JSONObject tmpRespJson = new JSONObject();
            if (StringHelper.isNullOrEmpty(pNtReq.getReqString())) {
                tmpRespJson.put("resultCode", "0");
                tmpRespJson.put("resultMessage", "接收请求数据为空,请检查请求数据格式!");
                resp.respBytes = JSON.toJSONString(tmpRespJson).getBytes(pNtReq.reqCharset);
                return resp;
            }

            String tmpStrRet = "success";

            try {
                JSONObject tmpJsonResp = null;
                try {
                    tmpJsonResp = JSONObject.parseObject(p_req);
                } catch (Exception ex) {
                    tmpRespJson.put("resultCode", "0");
                    tmpRespJson.put("resultMessage", "非法JSON,请检查请求数据格式!");
                    resp.respBytes = JSON.toJSONString(tmpRespJson).getBytes(pNtReq.reqCharset);
                    return resp;
                }

                if (tmpJsonResp.isEmpty()) {
                    tmpRespJson.put("resultCode", "0");
                    tmpRespJson.put("resultMessage", "请求JSON数据内容为空,请检查请求数据格式!");
                    resp.respBytes = JSON.toJSONString(tmpRespJson).getBytes(pNtReq.reqCharset);
                    return resp;
                }
                JSONObject bizContent = JSONObject.parseObject(tmpJsonResp.getString("msgContent"));
                WriteBankLogLn("消息体报文:\r\n" + JSON.toJSONString(bizContent));

                String reqSeqID = bizContent.getString("businessId");
                WriteBankLogLn("当前支付流水号:" + reqSeqID);

                WriteBankLogLn("通知结果文件保存本机目录:" + bankFront.bkTransFolder);
                File mdDir = new File(bankFront.bkTransFolder);
                if (!mdDir.exists()) {
                    mdDir.mkdirs();
                }

                String topic = getBankConfig().getSetValue("topic", "", "refund");
                WriteBankLogLn("本机退票主题:" + topic);
                String msgTopic = tmpJsonResp.getString("msgTopic");
                WriteBankLogLn("当前请求数据主题:" + msgTopic);
                if (StringHelper.hasAnyChar(topic) && msgTopic.equals(topic)) {
                    // 是退票
                    WriteBankLogLn("当前交易为退票数据...");
                    String refundDate = Format.Date8Format.format(new Date(Long.parseLong(bizContent.getString("tradeTime"))));
                    String localFilePath = StringHelper.trimEnd(bankFront.bkTransFolder, File.separator) + File.separator + bizContent.getString("companyAccount") + "_" + refundDate + ".txt";
                    WriteBankLogLn("当前交易结果保存本机路径:" + localFilePath);
                    File tmpLocalFile = new File(localFilePath);
                    if (tmpLocalFile.exists()) {
                        // 数据拼接
                        String tmpOrgData = FileHelper.readFileText(localFilePath, getCharset());
                        WriteBankLogLn("本机退票结果文件已有json数据:\r\n" + tmpOrgData);
                        String tmpRespArray = new String();
                        tmpRespArray = tmpOrgData + "\r\n" + bizContent.toJSONString();

                        WriteBankLogLn("拼接后本机退票json数据:\r\n" + tmpRespArray);
                        FileHelper.writeFile(localFilePath, tmpRespArray, getCharset());
                        WriteBankLogLn("当前退票结果保存本机成功.");
                        WriteBankLogLn("当前退票结果本机文件内容:\r\n" + FileHelper.readFileText(localFilePath, getCharset()));
                    } else {
                        // 直接写入
                        String tmpRespArray = new String();
                        tmpRespArray = bizContent.toJSONString();
                        WriteBankLogLn("写入本机退票结果文件数据为:\r\n" + tmpRespArray);
                        FileHelper.writeFile(localFilePath, tmpRespArray, getCharset());
                        WriteBankLogLn("当前退票结果保存本机成功.");
                        WriteBankLogLn("当前退票结果本机文件内容:\r\n" + FileHelper.readFileText(localFilePath, getCharset()));
                    }
                } else {
                    if (reqSeqID.contains("_")) {
                        // 批量的代码
                        String localFilePath = StringHelper.trimEnd(bankFront.bkTransFolder, File.separator) + File.separator + reqSeqID.split("_")[0] + ".txt";
                        WriteBankLogLn("当前交易结果保存本机路径:" + localFilePath);
                        File tmpLocalFile = new File(localFilePath);
                        if (tmpLocalFile.exists()) {
                            // 数据拼接
                            String tmpOrgData = FileHelper.readFileText(localFilePath, getCharset());
                            WriteBankLogLn("本机结果文件已有json数据:\r\n" + tmpOrgData);
                            String tmpRespArray = new String();
                            tmpRespArray = tmpOrgData + "\r\n" + bizContent.toJSONString();

                            WriteBankLogLn("拼接后本机json数据:\r\n" + tmpRespArray);
                            FileHelper.writeFile(localFilePath, tmpRespArray, getCharset());
                            WriteBankLogLn("当前交易结果保存本机成功.");
                            WriteBankLogLn("当前交易结果本机文件内容:\r\n" + FileHelper.readFileText(localFilePath, getCharset()));
                        } else {
                            // 直接写入
                            String tmpRespArray = new String();
                            tmpRespArray = bizContent.toJSONString();
                            WriteBankLogLn("写入本机结果文件数据为:\r\n" + tmpRespArray);
                            FileHelper.writeFile(localFilePath, tmpRespArray, getCharset());
                            WriteBankLogLn("当前交易结果保存本机成功.");
                            WriteBankLogLn("当前交易结果本机文件内容:\r\n" + FileHelper.readFileText(localFilePath, getCharset()));
                        }
                    } else {
                        // 单笔的代码
                        SeqSingleInfoHelper seqSingHelper = null;
                        SeqSingleInfo singleInfo = seqSingHelper.loadFromDb("EPAY01", reqSeqID);
                        String tmpStr = JSON.toJSONString(bizContent);
                        if (StringHelper.hasAnyChar(tmpStr)) {
                            String[] tmpStrJson = tmpStr.split("\r\n");
                            for (String s : tmpStrJson) {
                                s = "[" + s + "]";
                                JSONArray tmpRespArray = JSONArray.parseArray(s);
                                for (int i = 0; i < tmpRespArray.size(); i++) {
                                    JSONObject tmpRespObj = tmpRespArray.getJSONObject(i);
                                    String askNumber = tmpRespObj.getString("businessId").split("_")[1];
                                    String transState = tmpRespObj.getString("tradeState");
                                    String payInfoCode = "";
                                    if (tmpRespObj.containsKey("errorCode")) {
                                        payInfoCode = tmpRespObj.getString("tradeState") + "+" + tmpRespObj.getString("errorCode");
                                    } else {
                                        payInfoCode = tmpRespObj.getString("tradeState");
                                    }
                                    String respInfo = tmpRespObj.getString("errorMessage");

                                    if (askNumber.equals(singleInfo.askNumber)) {
                                        singleInfo.payState = transState;
                                        singleInfo.payInfoCode = payInfoCode;
                                        singleInfo.payInfo = respInfo;
                                    } else {
                                        singleInfo.payInfo = "处理完成";
                                        singleInfo.payState = "0000";
                                        singleInfo.payInfoCode = "0000";
                                    }
                                    seqSingHelper.updateTransState(singleInfo);
                                }
                            }
                        } else {
                            singleInfo.payInfo = "处理完成";
                            singleInfo.payState = "0000";
                            singleInfo.payInfoCode = "0000";
                            seqSingHelper.updateTransState(singleInfo);
                        }
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                tmpStrRet = ex.getMessage();
                WriteBankLogLn(ex);
            }

            if ("success".equals(tmpStrRet)) {
                tmpRespJson.put("resultCode", "1");
                tmpRespJson.put("resultMessage", "成功");
            } else {
                tmpRespJson.put("resultCode", "0");
                tmpRespJson.put("resultMessage", tmpStrRet);
            }
            String tmpResultJson = JSON.toJSONString(tmpRespJson);
            WriteBankLogLn("响应json:" + tmpResultJson);
            resp.respBytes = tmpResultJson.getBytes(pNtReq.reqCharset);
        }

        return resp;
    }

    @Override
    public void getContentLength(SocketReceiver p_receiver) throws Exception {
    }
}